package com.cykj.page02;

import com.cykj.page02.servlet.BaseServlet;
import com.cykj.page02.servlet.EnrollServlet;
import com.cykj.page02.servlet.LoginServlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page05
 * @Author: 阿隆
 * @CreateTime: 2025-10-18 16:19
 * @Description: TODO
 * @Version: 1.0
 */
public class ThreeServeToDynamicServlet {
    public static void main(String[] args) {
        try {
            //创建ServerSocket => 服务器
            ServerSocket serverSocket = new ServerSocket(9090);

            System.out.println("服务端启动端口号为: 9090");

            while (true) {

                //等待客户端连接  阻塞
                Socket socket = serverSocket.accept();

                //读取客户端发送的消息
                InputStream is = socket.getInputStream();

                byte[] bytes = new byte[1024];

                //读取
                int len = is.read(bytes);

                //请求消息
                String request = new String(bytes, 0, len);


                System.out.println(request);


                //解析消息
                MyHttpRequest httpRequest = new MyHttpRequest(request);

                //响应数据
                MyHttpResponse httpResponse = new MyHttpResponse(socket);

                //判断是静态资源 还是动态资源
                // / ==> http://127.0.0.1:9090/  ==> 展示首页
                if (httpRequest.getRequestModel().contains(".") || httpRequest.getRequestModel().equals("/")) {
                    //拼接完整路径
                    String resourcePath = "webapps" + httpRequest.getRequestUrl();

                    //静态资源处理器
                    StaticResourceHandler staticResourceHandler = new StaticResourceHandler(resourcePath);


                    httpResponse.write(staticResourceHandler.getMedia(), staticResourceHandler.getFileByte());

                } else {

                    switch (httpRequest.getRequestModel()) {
                        case "/login":

                            LoginServlet loginServlet = new LoginServlet();
                            loginServlet.requestMethodHandler(httpRequest , httpResponse);

                            break;
                        case "/enroll":
                            new EnrollServlet().requestMethodHandler(httpRequest , httpResponse);

                            break;
                        default:
                            //响应404
                            StaticResourceHandler staticResourceHandler = new StaticResourceHandler("webapps/pages/404.html");
                            httpResponse.write(staticResourceHandler.getFileByte());
                            break;
                    }
                }


            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
